// src/stores/modules/ai.js
import { defineStore } from 'pinia';
import AxiosMethods from '@/utils/AxiosMethods';

export const useAiStore = defineStore('ai', {
  state: () => ({
    aiData: {
      ask: '',
      answer: ''
    },
    historyList: []
  }),
  actions: {
    async fetchAiData(message) { // 询问AI部分
      this.aiData.ask = message;
      const response = await AxiosMethods.get('ai/generate', { params: { message } });
      this.aiData.answer = response.data.data;
      console.log(this.aiData.ask, this.aiData.answer);
    },
    
    async saveHistory(user, historyData) {// 保存历史记录到后端部分
      try {
        const response = await AxiosMethods.post('ai/batch', historyData);
        // console.log(response.data);
        if (response.data.code === true) {
          ElMessage.success('历史记录保存成功');
          this.historyList = historyData;
        } else {
          ElMessage.error('保存历史记录失败');
        }
      } catch (error) {
        console.error('保存历史记录失败:', error);
        ElMessage.error('保存历史记录失败');
      }
    },
    async fetchHistory(user) {// 从后端获取历史记录部分
      try {
        const response = await AxiosMethods.get('ai/user/' + user.data.id);
        if (response.data.code === 200) {
          this.historyList = response.data.data.records;
        } else {
          ElMessage.error('获取历史记录失败');
        }
      } catch (error) {
        console.error('获取历史记录失败:', error);
        ElMessage.error('获取历史记录失败');
      }
    }
  }
});
